package cn.dlc.com.client;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.dlc.com.config.Config;

public class ZookeeperClient implements Runnable {
	
	private String nodePath = "/config";

	private Config config;

	@Override
	public void run() {
		ZkClient zkClient = new ZkClient(
				new ZkConnection("192.168.182.88:2181,192.168.182.89:2181,192.168.182.90:2181", 5000));
		
		// 获取最初的节点信息
		ObjectMapper objectMapper = new ObjectMapper();
		String configStr = zkClient.readData(nodePath);
		try {
			config = objectMapper.readValue(configStr, Config.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(config.toString());
		// 监听数据的变化
		zkClient.subscribeDataChanges(nodePath, new IZkDataListener() {

			@Override
			public void handleDataDeleted(String dataPath) throws Exception {
				if (dataPath.equals(nodePath)) {
					System.out.println("节点：" + dataPath + "被删除了！");
				}
			}

			@Override
			public void handleDataChange(String dataPath, Object data) throws Exception {
				if (dataPath.equals(nodePath)) {
					System.out.println("节点：" + dataPath + ", 数据被修改了");
					
					ObjectMapper objectMapper = new ObjectMapper();
					String configStr = zkClient.readData(nodePath);
					try {
						config = objectMapper.readValue(configStr, Config.class);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println("新的节点信息： " + config.toString());
				}
			}
		});
	}
}
